package io.framework.modules.security.controller;

import cn.com.digitalhainan.apione.sdk.HttpCaller;
import cn.com.digitalhainan.apione.sdk.HttpParameters;
import cn.com.digitalhainan.apione.sdk.ContentBody;
import cn.com.digitalhainan.apione.sdk.HttpReturn;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.framework.common.exception.ErrorCode;
import io.framework.common.exception.RenException;
import io.framework.common.utils.IpUtils;
import io.framework.common.utils.Result;
import io.framework.common.validator.AssertUtils;
import io.framework.common.validator.ValidatorUtils;
import io.framework.modules.log.entity.SysLogLoginEntity;
import io.framework.modules.log.enums.LoginOperationEnum;
import io.framework.modules.log.enums.LoginStatusEnum;
import io.framework.modules.log.service.SysLogLoginService;
import io.framework.modules.security.user.SecurityUser;
import io.framework.modules.security.user.UserDetail;
import io.framework.modules.sys.dto.SysUserDTO;
import io.framework.modules.sys.enums.UserStatusEnum;
import io.framework.modules.security.dto.LoginDTO;
import io.framework.modules.security.password.PasswordUtils;
import io.framework.modules.security.service.CaptchaService;
import io.framework.modules.sys.service.SysUserService;
import io.framework.modules.security.service.SysUserTokenService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.xmlbeans.GDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录
 * 
 *
 */
@RestController
@Api(tags="登录管理")
public class LoginController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private CaptchaService captchaService;
	@Autowired
	private SysLogLoginService sysLogLoginService;

	@GetMapping("captcha")
	@ApiOperation(value = "验证码", produces = "application/octet-stream")
	@ApiImplicitParam(paramType = "query", dataType = "string", name = "uuid", required = true)
	public void captcha(HttpServletResponse response, String uuid) throws IOException {
		//uuid不能为空
		AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);

		//生成图片验证码
		BufferedImage image = captchaService.create(uuid);

		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.close();
	}

	@PostMapping("login")
	@ApiOperation(value = "登录")
	public Result login(HttpServletRequest request, @RequestBody LoginDTO login) {
		try {
			//效验数据
		//	ValidatorUtils.validateEntity(login);
			//用户信息
			SysUserDTO user = sysUserService.getByUsername(login.getUsername());

			System.out.println("user"+user.getUsername());

			SysLogLoginEntity log = new SysLogLoginEntity();
			log.setOperation(LoginOperationEnum.LOGIN.value());
			log.setCreateDate(new Date());
			log.setIp(IpUtils.getIpAddr(request));
			log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
			log.setIp(IpUtils.getIpAddr(request));

			//用户不存在
			if (user == null) {
				log.setStatus(LoginStatusEnum.FAIL.value());
				log.setCreatorName(login.getUsername());
				sysLogLoginService.save(log);
				System.out.println("user is null ");

				throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
			}

			//密码错误
			if (!PasswordUtils.matches(login.getPassword(), user.getPassword())) {
				log.setStatus(LoginStatusEnum.FAIL.value());
				log.setCreator(user.getId());
				log.setCreatorName(user.getUsername());
				sysLogLoginService.save(log);

				System.out.println("user is password error ");
				throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
			}

			//账号停用
			if (user.getStatus() == UserStatusEnum.DISABLE.value()) {
				log.setStatus(LoginStatusEnum.LOCK.value());
				log.setCreator(user.getId());
				log.setCreatorName(user.getUsername());
				sysLogLoginService.save(log);

				throw new RenException(ErrorCode.ACCOUNT_DISABLE);
			}

			//登录成功
			System.out.println("user is success ");

			log.setStatus(LoginStatusEnum.SUCCESS.value());
			log.setCreator(user.getId());
			log.setCreatorName(user.getUsername());
			sysLogLoginService.save(log);

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH：表示24小时制，hh：表示12小时制

			String newdate = format.format(new Date());
			String date = format.format(user.getUpdateDate());
			String flag = "0";
			try {
				Date newdate1 = format.parse(newdate);
				Date date1 = format.parse(date);
				int days = (int) ((newdate1.getTime() - date1.getTime()) / (1000 * 3600 * 24));
				if (days >= 180) {
					flag = "1";
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}


			return sysUserTokenService.createToken(user.getId(), flag);
		} catch (Exception e) {
			return new Result().error(e.toString());
		}


	}

	@PostMapping("logout")
	@ApiOperation(value = "退出")
	public Result logout(HttpServletRequest request) {
		UserDetail user = SecurityUser.getUser();

		//退出
		sysUserTokenService.logout(user.getId());

		//用户信息
		SysLogLoginEntity log = new SysLogLoginEntity();
		log.setOperation(LoginOperationEnum.LOGOUT.value());
		log.setIp(IpUtils.getIpAddr(request));
		log.setUserAgent(request.getHeader(HttpHeaders.USER_AGENT));
		log.setIp(IpUtils.getIpAddr(request));
		log.setStatus(LoginStatusEnum.SUCCESS.value());
		log.setCreator(user.getId());
		log.setCreatorName(user.getUsername());
		log.setCreateDate(new Date());
		sysLogLoginService.save(log);

		return new Result();
	}


	/**
	 * 海政通登录
	 *
	 * @return
	 */
	@ApiOperation(value = "海政通登录", notes = "系统登陆，通过token验证用户信息")
	@PostMapping(value = "/hztLogin")
	public Result getUaaUserInfo(@RequestBody Map<String, Object> params) {

		String apiName = "uaaUserDetailByToken";
//		String apiName = "uaaUserDetailByTokenTest";

		String authorization = "Bearer " + params.get("accessToken");
		System.out.println("------------------196 token------------");
		System.out.println(authorization);
		HashMap<String, String> header = new HashMap<>();

		header.put("Authorization", authorization);
		header.put("Uaa-App-Key", "AK9065f1aa038f47bb9244853653530018"); // 海政通团队提供
		header.put("Uaa-Tenant-Id", "1");
		HttpParameters parameters = HttpParameters.builder()
				.api(apiName)
				.region("INTER")
				.headerParamsMap(header)
				.accessKey("AKc87d568fd40e450fa511dcf73704ee7a") // 海政通团队提供
				.secretKey("SKbabac6d55f9d4082b534499c3b3a1295") // 海政通团队提供
				.contentBody(new ContentBody(""))
				.requestUrl("https://api-one.digitalhainan.com.cn/apione"
				)
				.build();
		HttpReturn call = HttpCaller.getInstance().call(parameters);
		System.out.println("------------------213------------");
		System.out.println(call.toString());
		JSONObject apiResultObject = JSON.parseObject(call.response);
		if (apiResultObject.getBoolean("success")) {
			JSONObject hztUser = apiResultObject.getJSONObject("data");
			//用户手机号
			String realName = hztUser.getString("nickName");
			//用户信息
			SysUserDTO user = sysUserService.getByRealName(realName);

			SysLogLoginEntity log = new SysLogLoginEntity();
			log.setOperation(LoginOperationEnum.LOGIN.value());
			log.setCreateDate(new Date());


			//用户不存在
			if (user == null) {
				log.setStatus(LoginStatusEnum.FAIL.value());
				log.setCreatorName("ck");
				sysLogLoginService.save(log);

				throw new RenException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
			}

			//登录成功
			log.setStatus(LoginStatusEnum.SUCCESS.value());
			log.setCreator(user.getId());
			log.setCreatorName(user.getUsername());
			sysLogLoginService.save(log);

			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//HH：表示24小时制，hh：表示12小时制

			String newdate = format.format(new Date());
			String date = format.format(user.getUpdateDate());
			String flag = "0";
			try {
				Date newdate1 = format.parse(newdate);
				Date date1 = format.parse(date);
				int days = (int) ((newdate1.getTime() - date1.getTime()) / (1000 * 3600 * 24));
				if (days >= 180) {
					flag = "1";
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}

			return sysUserTokenService.createToken(user.getId(), flag);
		}
		return null;
	}


}